from flask import Flask, render_template, request, jsonify, session
import json
import os
from datetime import datetime, timedelta
import uuid

app = Flask(__name__)
app.secret_key = 'loan-app-secret-key-2024'

# 模拟数据库
USERS_FILE = 'users.json'
LOANS_FILE = 'loans.json'

def init_data_files():
    """初始化数据文件"""
    if not os.path.exists(USERS_FILE):
        with open(USERS_FILE, 'w', encoding='utf-8') as f:
            json.dump({}, f, ensure_ascii=False, indent=2)
    
    if not os.path.exists(LOANS_FILE):
        with open(LOANS_FILE, 'w', encoding='utf-8') as f:
            json.dump({}, f, ensure_ascii=False, indent=2)

def load_data(filename):
    """加载数据"""
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return json.load(f)
    except:
        return {}

def save_data(filename, data):
    """保存数据"""
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

@app.route('/')
def index():
    """首页"""
    return render_template('index.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    """用户注册"""
    if request.method == 'POST':
        data = request.get_json()
        users = load_data(USERS_FILE)
        
        phone = data.get('phone')
        if phone in users:
            return jsonify({'success': False, 'message': '手机号已注册'})
        
        user_id = str(uuid.uuid4())
        users[phone] = {
            'id': user_id,
            'phone': phone,
            'password': data.get('password'),
            'name': '',
            'id_card': '',
            'created_at': datetime.now().isoformat()
        }
        save_data(USERS_FILE, users)
        
        return jsonify({'success': True, 'message': '注册成功'})
    
    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    """用户登录"""
    if request.method == 'POST':
        data = request.get_json()
        users = load_data(USERS_FILE)
        
        phone = data.get('phone')
        password = data.get('password')
        
        if phone in users and users[phone]['password'] == password:
            session['user_phone'] = phone
            session['user_id'] = users[phone]['id']
            return jsonify({'success': True, 'message': '登录成功'})
        
        return jsonify({'success': False, 'message': '手机号或密码错误'})
    
    return render_template('login.html')

@app.route('/logout')
def logout():
    """退出登录"""
    session.clear()
    return jsonify({'success': True, 'message': '已退出登录'})

@app.route('/identity')
def identity():
    """身份认证页面"""
    if 'user_phone' not in session:
        return render_template('login.html')
    return render_template('identity.html')

@app.route('/api/identity', methods=['POST'])
def api_identity():
    """提交身份认证"""
    if 'user_phone' not in session:
        return jsonify({'success': False, 'message': '请先登录'})
    
    data = request.get_json()
    users = load_data(USERS_FILE)
    
    phone = session['user_phone']
    users[phone]['name'] = data.get('name')
    users[phone]['id_card'] = data.get('id_card')
    save_data(USERS_FILE, users)
    
    return jsonify({'success': True, 'message': '身份认证成功'})

@app.route('/loan-apply')
def loan_apply():
    """贷款申请页面"""
    if 'user_phone' not in session:
        return render_template('login.html')
    return render_template('loan-apply.html')

@app.route('/api/loan-apply', methods=['POST'])
def api_loan_apply():
    """提交贷款申请"""
    if 'user_phone' not in session:
        return jsonify({'success': False, 'message': '请先登录'})
    
    data = request.get_json()
    users = load_data(USERS_FILE)
    loans = load_data(LOANS_FILE)
    
    phone = session['user_phone']
    user = users[phone]
    
    if not user.get('name') or not user.get('id_card'):
        return jsonify({'success': False, 'message': '请先完成身份认证'})
    
    loan_id = str(uuid.uuid4())
    amount = float(data.get('amount', 0))
    period = int(data.get('period', 1))
    
    # 简单的额度评估逻辑
    max_amount = 5000  # 默认最大额度
    if len(user.get('id_card', '')) == 18:
        max_amount = 10000
    
    if amount > max_amount:
        return jsonify({'success': False, 'message': f'申请金额超出额度，最高可申请{max_amount}元'})
    
    # 计算利息和还款计划
    monthly_rate = 0.015  # 月利率1.5%
    total_interest = amount * monthly_rate * period
    total_amount = amount + total_interest
    monthly_payment = total_amount / period
    
    loan = {
        'id': loan_id,
        'user_id': user['id'],
        'phone': phone,
        'amount': amount,
        'period': period,
        'purpose': data.get('purpose', ''),
        'status': 'pending',  # pending, approved, rejected
        'apply_date': datetime.now().isoformat(),
        'approve_date': None,
        'monthly_rate': monthly_rate,
        'total_interest': total_interest,
        'total_amount': total_amount,
        'monthly_payment': monthly_payment,
        'next_payment_date': None
    }
    
    loans[loan_id] = loan
    save_data(LOANS_FILE, loans)
    
    return jsonify({'success': True, 'message': '申请已提交', 'loan_id': loan_id})

@app.route('/loan-status')
def loan_status():
    """贷款状态页面"""
    if 'user_phone' not in session:
        return render_template('login.html')
    return render_template('loan-status.html')

@app.route('/api/loan-status')
def api_loan_status():
    """获取贷款状态"""
    if 'user_phone' not in session:
        return jsonify({'success': False, 'message': '请先登录'})
    
    loans = load_data(LOANS_FILE)
    user_loans = []
    
    for loan_id, loan in loans.items():
        if loan['phone'] == session['user_phone']:
            # 模拟审批过程
            if loan['status'] == 'pending':
                import random
                if random.random() < 0.8:  # 80%概率通过
                    loan['status'] = 'approved'
                    loan['approve_date'] = datetime.now().isoformat()
                    loan['next_payment_date'] = (datetime.now() + timedelta(days=30)).isoformat()
                else:
                    loan['status'] = 'rejected'
                save_data(LOANS_FILE, loans)
            
            user_loans.append(loan)
    
    return jsonify({'success': True, 'loans': user_loans})

@app.route('/repayment')
def repayment():
    """还款页面"""
    if 'user_phone' not in session:
        return render_template('login.html')
    return render_template('repayment.html')

@app.route('/api/repayment/<loan_id>')
def api_repayment(loan_id):
    """获取还款详情"""
    if 'user_phone' not in session:
        return jsonify({'success': False, 'message': '请先登录'})
    
    loans = load_data(LOANS_FILE)
    
    if loan_id not in loans or loans[loan_id]['phone'] != session['user_phone']:
        return jsonify({'success': False, 'message': '贷款不存在'})
    
    loan = loans[loan_id]
    
    # 生成还款计划
    if loan['status'] != 'approved':
        return jsonify({'success': False, 'message': '贷款未通过审批'})
    
    repayment_plan = []
    start_date = datetime.fromisoformat(loan['approve_date'])
    
    for i in range(1, loan['period'] + 1):
        payment_date = start_date + timedelta(days=30 * i)
        repayment_plan.append({
            'period': i,
            'payment_date': payment_date.isoformat()[:10],
            'amount': loan['monthly_payment'],
            'status': 'pending' if payment_date > datetime.now() else 'paid'
        })
    
    return jsonify({
        'success': True,
        'loan': loan,
        'repayment_plan': repayment_plan
    })

if __name__ == '__main__':
    init_data_files()
    app.run(debug=True, host='0.0.0.0', port=5000)
